package cn.lenchu.data.h2.dao;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.lenchu.data.dao.UserDao;
import cn.lenchu.data.h2.converter.UserConverter;
import cn.lenchu.data.h2.entity.UserEntity;
import cn.lenchu.data.h2.repository.UserRepository;
import cn.lenchu.data.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Optional;

/**
 * @author lenchu
 */
@Service
public class UserDaoImpl implements UserDao {

    @Autowired
    private UserRepository userRepository;

    @Override
    public User findById(Integer id) {
        Optional<UserEntity> userEntityOptional = userRepository.findById(id);
        if (userEntityOptional.isPresent()) {
            UserEntity userEntity = userEntityOptional.get();
            return UserConverter.toUser(userEntity);
        }
        return null;
    }

    @Override
    public User findOneByEmail(String email) {
        Optional<UserEntity> userEntityOptional = userRepository.findByEmail(email);
        if (userEntityOptional.isPresent()) {
            UserEntity userEntity = userEntityOptional.get();
            return UserConverter.toUser(userEntity);
        }
        return null;
    }

    @Override
    public User findOneByMobile(String mobile) {
        Optional<UserEntity> userEntityOptional = userRepository.findByMobile(mobile);
        if (userEntityOptional.isPresent()) {
            UserEntity userEntity = userEntityOptional.get();
            return UserConverter.toUser(userEntity);
        }
        return null;
    }

    @Override
    public User upsert(User user) {
        UserEntity userEntity = UserConverter.toUserEntity(user);
        Timestamp now = Timestamp.valueOf(LocalDateTime.now());
        if (user.getId() == null) {
            userEntity.setCreateTime(now);
            return UserConverter.toUser(userRepository.saveAndFlush(userEntity));
        } else {
            Optional<UserEntity> userEntityOptional = userRepository.findById(user.getId());
            if (userEntityOptional.isPresent()) {
                UserEntity entity = userEntityOptional.get();
                BeanUtil.copyProperties(userEntity, entity, CopyOptions.create().ignoreNullValue().ignoreError());
                entity.setUpdateTime(now);
                return UserConverter.toUser(userRepository.saveAndFlush(entity));
            }
        }
        return null;
    }
}
